﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomsSystem.BLL;
using System.Data;
using CustomsSystem.Common;
using Maticsoft.Common;

namespace WEB.sheetInfo
{
    public partial class CustomSheetView : sheetView
    {
        static DataSet ds;
        static Table tableContent;
        protected new void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.tbTimestart.Attributes.Add("onClick", "new WdatePicker()");
                this.tbTimestop.Attributes.Add("onClick", "new WdatePicker()");
                
                //初始化日期范围
                DateTime now=DateTime.Now;
                tbTimestop.Text = now.ToShortDateString();
                tbTimestart.Text = now.AddMonths(-1).ToShortDateString();

                BindData();
            }
            if (Session["tableCalc"] != null)
            {
                tableContent = (Table)Session["tableCalc"];
            }
        }

        private void BindData()
        {
            SheetInfoManage sheetManage = new SheetInfoManage();
            //搜索分页数据
            //判断搜索条件
            ds = sheetManage.GetViewByCalc(Query());
            gvSheetInfo.DataSource = ds;
            WhichColunmNeedShow();
            Label lbl = new Label();
            //统计信息
            AddCalcTabelRow();
            //lbl.Text = string.Format("合计:<span style=\"color:red;font-size:20pt;\">{0}</span>票业务，数量合计：<span style=\"color:red;font-size:20pt;\">{1}</span>，毛重合计：<span style=\"color:red;font-size:20pt;\">{2}</span>，货值合计：<span style=\"color:red;font-size:20pt;\">{3}</span>"
                //, ds.Tables[0].Rows.Count, CalcTheInfo(CALC_TYPE.NO), CalcTheInfo(CALC_TYPE.GOOD_W), CalcTheInfo(CALC_TYPE.GOOD_V));
            //panelCalc.Controls.Add(lbl);
            gvSheetInfo.DataBind();
        }

        private void AddCalcTabelRow()
        {
            if (tbTimestart.Text == "" || tbTimestop.Text == "") return;
            TimeSpan tSpan= Convert.ToDateTime(tbTimestop.Text) - Convert.ToDateTime(tbTimestart.Text);
            DataView dv = ds.Tables[0].DefaultView;
            dv.Sort = "agencyDate Asc";
            DataTable dt = dv.ToTable();
            List<int> listIn = new List<int>();
            List<int> listOut = new List<int>();
            List<int> listBJ = new List<int>();
            List<int> listJQ = new List<int>();
            List<int> listWXP = new List<int>();
            List<int> listOther = new List<int>();
            List<int> listSum = new List<int>();
            List<int> listBox = new List<int>();
            List<decimal> listGoods_w = new List<decimal>();
            for (int i = 0; i <= tSpan.Days; i++)
            {
                DateTime tmpDate = Convert.ToDateTime(tbTimestart.Text).AddDays(i);
                dv.RowFilter = string.Format("agencyDate = #{0}#",tmpDate.ToShortDateString());
                dt = dv.ToTable();
                if (dt.Rows.Count <= 0) continue;
                int sum = 0 , res = 0;
                TableRow tr = new TableRow();
                TableCell tc1 = new TableCell();
                tc1.Text = tmpDate.ToShortDateString();
                tr.Cells.Add(tc1);
                //进口
                TableCell tcIn = new TableCell();
                res = CalcColunm(dt, "codeName1 like '%进口%' and (typeID = '报关报检' or typeID = '单独报关')");
                listIn.Add(res);
                sum += res;
                tcIn.Text = res.ToString();
                tr.Cells.Add(tcIn);
                //出口
                TableCell tcOut = new TableCell();
                res = CalcColunm(dt, "codeName1 like '%出口%' and (typeID = '报关报检' or typeID = '单独报关')");
                listOut.Add(res);
                sum += res;
                tcOut.Text = res.ToString();
                tr.Cells.Add(tcOut);
                //报检
                TableCell tcBj = new TableCell();
                res = CalcColunm(dt, "typeID = '单独报检'");
                listBJ.Add(res);
                sum += res;
                tcBj.Text = res.ToString();
                tr.Cells.Add(tcBj);
                //加签
                TableCell tcJQ = new TableCell();
                res = CalcColunm(dt, "typeID = '加签'");
                listJQ.Add(res);
                sum += res;
                tcJQ.Text = res.ToString();
                tr.Cells.Add(tcJQ);
                //危险品
                TableCell tcWXP = new TableCell();
                res = CalcColunm(dt, "typeID = '危险品'");
                listWXP.Add(res);
                sum += res;
                tcWXP.Text = res.ToString();
                tr.Cells.Add(tcWXP);
                //其他
                TableCell tcOther = new TableCell();
                res = CalcColunm(dt, "typeID = '其他'");
                listOther.Add(res);
                sum += res;
                tcOther.Text = res.ToString();
                tr.Cells.Add(tcOther);
                //
                //总数
                TableCell tc5 = new TableCell();
                listSum.Add(sum);
                tc5.Text = sum.ToString();
                tr.Cells.Add(tc5);
                //集装箱
                TableCell tc6 = new TableCell();
                res = CalcBoxSum(dt);
                listBox.Add(res);
                tc6.Text = res.ToString();
                tr.Cells.Add(tc6);
                //重量
                TableCell tc7 = new TableCell();
                object tmp = dt.Compute("Sum(grossWeight)", dv.RowFilter);
                decimal goodsWeight = 0;
                if(tmp!=DBNull.Value)  goodsWeight =Convert.ToDecimal(tmp);
                listGoods_w.Add(goodsWeight);
                //res = CalcColunm(dt, "Sum(Child.'grossWeight')");
                tc7.Text = goodsWeight.ToString();
                tr.Cells.Add(tc7);
                tableCalc.Rows.Add(tr);
            }
            TableRow trEnd = new TableRow();
            TableCell tcEnd1 = new TableCell();
            tcEnd1.Text = "合计:";
            trEnd.Cells.Add(tcEnd1);
            TableCell tcEnd2 = new TableCell();
            tcEnd2.Text = listIn.Sum().ToString() ;
            trEnd.Cells.Add(tcEnd2);
            TableCell tcEnd3 = new TableCell();
            tcEnd3.Text = listOut.Sum().ToString();
            trEnd.Cells.Add(tcEnd3);
            TableCell tcEnd4 = new TableCell();
            tcEnd4.Text = listBJ.Sum().ToString();
            trEnd.Cells.Add(tcEnd4);
            TableCell tcEnd5 = new TableCell();
            tcEnd5.Text = listJQ.Sum().ToString();
            trEnd.Cells.Add(tcEnd5);
            TableCell tcEnd6 = new TableCell();
            tcEnd6.Text = listWXP.Sum().ToString();
            trEnd.Cells.Add(tcEnd6);
            TableCell tcEnd7 = new TableCell();
            tcEnd7.Text = listOther.Sum().ToString();
            trEnd.Cells.Add(tcEnd7);
            TableCell tcEnd8 = new TableCell();
            tcEnd8.Text = listSum.Sum().ToString();
            trEnd.Cells.Add(tcEnd8);
            TableCell tcEnd9 = new TableCell();
            tcEnd9.Text = listBox.Sum().ToString();
            trEnd.Cells.Add(tcEnd9);
            TableCell tcEnd10 = new TableCell();
            tcEnd10.Text = listGoods_w.Sum().ToString();
            trEnd.Cells.Add(tcEnd10);
            tableCalc.Rows.Add(trEnd);
            Session["tableCalc"] = tableCalc;
        }


        private void WhichColunmNeedShow()
        {
            GridViewRow gvr = gvSheetInfo.HeaderRow;
            if (gvr == null) return;
            for (int i = 0; i < gvr.Cells.Count; i++)
            {
                if (gvSheetInfo.Columns[i] is BoundField)
                {
                    string df = ((BoundField)gvSheetInfo.Columns[i]).DataField;
                    if (panelCondition.FindControl("cb" + df) is CheckBox)
                    {
                        CheckBox cb = panelCondition.FindControl("cb" + df) as CheckBox;
                        if (cb.Checked)
                        {
                            gvSheetInfo.Columns[i].Visible = true;
                        }
                        else
                        {
                            gvSheetInfo.Columns[i].Visible = false;
                        }
                    }
                }
                
            }
        }


        /// <summary>
        /// 增加筛选选项
        /// </summary>
        private void AddConditionToPanel()
        {
            GridViewRow gvr = gvSheetInfo.HeaderRow;
            if (gvr == null) return;
            for (int i = 0; i < gvr.Cells.Count; i++)
            {
                CheckBox cbNew = new CheckBox();
                if (gvSheetInfo.Columns[i] is BoundField)
                {
                    cbNew.ID = "cb" + ((BoundField)gvSheetInfo.Columns[i]).DataField;
                    cbNew.Text = gvr.Cells[i].Text;
                    cbNew.Checked = true;
                }
                    
                if (cbNew.Text != "" && cbNew.Text != "&nbsp;")
                {
                    if (panelCondition.Controls[i] is CheckBox)
                    {
                        CheckBox cbOld = panelCondition.Controls[i] as CheckBox;
                        if (cbOld != null) cbOld = cbNew;
                    }
                }
            }
        }

        /// <summary>
        /// 统计字段枚举
        /// </summary>
        public enum CALC_TYPE{
            NO,
            GOOD_W,
            GOOD_V
        }
        private string CalcTheInfo(CALC_TYPE type)
        {
            string res="";
            switch (type)
            {
                case CALC_TYPE.NO:
                    res = CalcColunm("NO",ds.Tables[0]);
                    break;
                case CALC_TYPE.GOOD_W:
                    res = CalcColunm("grossWeight",ds.Tables[0]);
                    break;
                case CALC_TYPE.GOOD_V:
                    res = CalcColunm("goodsValue",ds.Tables[0]);
                    break;
            }
            return res;
        }
        /// <summary>
        /// 统计某字段的值
        /// </summary>
        /// <param name="Colunm"></param>
        /// <returns></returns>
        private string CalcColunm(string ColunmName,DataTable dt)
        {
            if (dt == null) return "";
            decimal sum=0;
            for (int i = 0; i < ds.Tables[0].Rows.Count;i++)
            {
                string value = ds.Tables[0].Rows[i][ColunmName].ToString();
                if (Maticsoft.Common.PageValidate.IsDecimalSign(value) || Maticsoft.Common.PageValidate.IsNumberSign(value))
                {
                    sum += Convert.ToDecimal(ds.Tables[0].Rows[i][ColunmName]);
                }
            }
            return sum.ToString();
        }

        /// <summary>
        /// 根据条件统计某字段的行数
        /// </summary>
        /// <param name="Colunm"></param>
        /// <returns></returns>
        private int CalcColunm(DataTable dt, string condition)
        {
            if (dt == null) return 0;
            DataView dv = dt.DefaultView;
            dv.RowFilter = condition;
            return dv.ToTable().Rows.Count;
        }
        /// <summary>
        /// 专门计算标准箱数量的
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private int CalcBoxSum(DataTable dt)
        {
            if (dt == null) return 0;
            int sum = 0;
            //List<string> ContainerNos=new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string containerNo = dt.Rows[i]["No"].ToString();
                if (containerNo == "") continue;
                string [] ContainerNos = containerNo.Split(',');
                foreach(string str in ContainerNos)
                {
                    string nStr = str.Substring(0, 2);
                    if (!PageValidate.IsNumber(nStr)) continue;
                    int n = int.Parse(nStr);
                    string uni = str.Substring(str.Length-2, 2);
                    if (!PageValidate.IsNumber(uni)) continue;
                    int mud = int.Parse(uni) / 20;
                    sum += n * mud;
                }
                
            }
            return sum;
        }

        protected new void btnQuery_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected new void gvSheetInfo_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvSheetInfo.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected new void gvSheetInfo_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }

        protected void btnToExcel_Click(object sender, EventArgs e)
        {
            string fileName = "报关统计.xls";
            HtmlDataToDoc hdtd = new HtmlDataToDoc(this.Page);
            hdtd.TableDataToExcel(tableContent, fileName);
        }

        /// <summary>
        /// 需要在调用的页面中必须重写VerifyRenderingInServerForm方法，否则将出现错误
        /// </summary>
        public override void VerifyRenderingInServerForm( Control control )
        {
        }
    }
}